#include "stm32f4xx.h"
#include "IOI2C.h"
#include "ist8310.h"
#include "rtthread.h"

extern void Delay(u16 nTime);
/**
  * @name
  * @brief
  * @param  
  * @retval 
  */
u8 mag_reg = 0;
u8 mag_whoami = 0;
void IST8310_Init(void)
{

	IIC_Init();
	IICReadByte(IST8310_ADDRESS,IST8310_CONF_REG2,		&mag_reg);
	mag_reg = (mag_reg | 0x01);																								//soft reset ,write 1 @ bit0 
	while(!IICWriteByte(IST8310_ADDRESS,IST8310_CONF_REG2,	mag_reg));
	rt_thread_delay(50);
	while(!IICWriteByte(IST8310_ADDRESS,IST8310_PDCNTL,			0xC0));
	while(!IICWriteByte(IST8310_ADDRESS,IST8310_AVGCNTL,		0x24));						//x y z data average by 16times
	IICReadByte(IST8310_ADDRESS,IST8310_WHO_AM_I,		&mag_whoami);

//	rt_thread_mdelay(100);
	rt_thread_delay(500);
	rt_kprintf("Magnect Sensor IST8310 Setup Success!\n");

}

/**
  * @name						Read_MAG3axis
  * @brief				
  * @param  				MAGREG_TypeDef *sensor
  * @retval 				ret
  */
u8 Read_MAG3axis(MAGREG_TypeDef *sensor)
{
	u8 var[10];
	u8 ret;
	u8 dataRDY = 0;
	
	while(!IICWriteByte(IST8310_ADDRESS,IST8310_CONF_REG1,0x01));//switch to sigle measuremet mode
	
	while(!(dataRDY & 0x01))
	{IICReadByte(IST8310_ADDRESS,IST8310_STA_REG1,	&dataRDY);//wait until data ready regbit =1,
	}
	ret = IICReadBytes(IST8310_ADDRESS,IST8310_OUT_X_L,6,var);

	sensor->x_axis = (s16)( (var[1]<< 8)| var[0]);
	sensor->y_axis = (s16)( (var[3]<< 8)| var[2]);
	sensor->z_axis = (s16)( (var[5]<< 8)| var[4]);

	return ret;
}


/**
  * @name
  * @brief
  * @param  
  * @retval 
  */
void ReverseMagPor(bool dir)
{
	if(dir == FALSE)
	{while(!IICWriteByte(IST8310_ADDRESS,IST8310_SELF_TEST,0x40));
	}
	if(dir == TRUE)
	{while(!IICWriteByte(IST8310_ADDRESS,IST8310_SELF_TEST,0X00));
	}
}



/*******************************END OF FILE DRV_IST8310.C*******************************************/